import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app

import os
from google.appengine.ext.webapp import template

from models import *

class MainPage(webapp.RequestHandler):
	def verifyLogin(self):
		user = users.get_current_user()
		if user:
			usercheck=userDetails.all()
			usercheck.filter("email =",user.email())
			try:
				currentuser=usercheck.fetch(1)[0]
				userdet=db.GqlQuery("SELECT * FROM userDetails WHERE email='"+user.email()+"'")
				for i in userdet:
					if i.privilege=='user':
						return
					elif i.approved==False:
						self.redirect("/usererror")
						return
				self.redirect("/admin")
			except:
				path = os.path.join(os.path.dirname(__file__),'form.html')#use template
				self.response.out.write(template.render(path,{"email":user.email()}))#using template
		else:
			self.redirect(users.create_login_url(self.request.uri))

	def get(self):
	    self.verifyLogin()
            user = users.get_current_user()
	    template_values = { }
	    path = os.path.join(os.path.dirname(__file__), 'question.html')
	    self.response.out.write(template.render(path, template_values))
	
	def post(self):    
		x=self.request.get("t1")
		user = users.get_current_user()
		t_email=user.email()		
		usrdtl=db.GqlQuery("SELECT * FROM userDetails")
		for j in usrdtl:
			if j.email==t_email:
				user_ano=j.admissionnumber
				self.response.out.write(user_ano)

		tempvar=questionanswer(admissionnumber=str(user_ano),question=x)
		key=tempvar.put()
		tempvar.questionid=str(key.id())
		tempvar.put()
		self.redirect('/user')

application = webapp.WSGIApplication([('/question', MainPage)],debug=True)

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()
